<template>
	<view style="" >
		<camera :device-position="device" flash="off" 
		
			style="width: 400px;height: 400px;">
			
			<!-- style="height : `${autoHeight}`px;height : `${autoWidth}`px" -->
			
		</camera>
		<button  size="mini" @tap="switchDevice" style="z-index:100"> {{deviceName}}</button>
		<image type="default" @tap="onTakePhoto" :src="cameraIco"  style="width:40px;height:40px;z-index:100">拍照</image>
	</view>

</template>

<script>
	import {registerParamsEvent} from "../../common/js/util";
	import {
		upload,
		requestFile
	} from "../../common/js/request"; // upload 文件上传

	export default {
		data() {
			return {
                cameraIco: "../../static/icon/camera.png",
				autoHeight:400,
				autoWidth:400,
				device: 'front',
				deviceName: "前置相机",
				form: {
					purpose: "",
					imgurl: "",
					index: "",
					id: ""
				}
			};
		},
		mounted() {
			let ref = this;
			 uni.getSystemInfo({
			 	success: function(res) {
			 		ref.autoHeight = res.windowHeight;
			 		ref.autoWidth = res.windowWidth;
			 	}
			 });
            
            this.init();
		},
		
		methods: {
            init() {
                registerParamsEvent(({
                    purpose, disabled, index
				}) => {
                    this.form.purpose = purpose;
                    this.form.index = index; 
					this.disabled = disabled;
                    console.log("snapArgsInit completed");

                }, "itemCallback");
               
                uni.$emit("snapArgsInit", "itemCallback");
            },
            switchDevice() {
                this.device = this.device == "front" ? "back" : "front";
                this.deviceName = this.device == "front" ? "前置相机" : "后置相机";
            },
            onSnapCompleted(attach) {

                this.form.imgurl = attach.url;
				this.form.id = attach.id;				
				uni.$emit("snapCallback", this.form);

                uni.navigateBack({
                    delta: 1,
                    fail(err) {
                        console.log(err, '----------')
                    }
                });

            },
			onTakePhoto: function() {

                var ref = this;
				const camera = uni.createCameraContext() //创建照相机对象
				camera.takePhoto({ //实现拍照功能
					quality: 'high', //high 高质量成像、 normal 普通质量、row 低质量
					success: (res) => {
						
						//ref.onSnapCompleted({
						//	id: 1,
						//	url: res.tempImagePath							
						//});
						//return;

						var ImageData = res.tempImagePath;
						// #ifdef   MP-WEIXIN
						/////////////////////////// MP-WX
						upload(
							ImageData
						).then(data => {
							ref.onSnapCompleted(data);
							
						});
						// #endif

					}
				})
			}

		}
	};
</script>

<style scoped>
	
</style>
